
<template>
  <view class="container">

      <!-- 自定义标题栏 -->
      <navigationBar :title="title" id="top" ref="navigationBar"></navigationBar>
      <!-- 内容区域 -->
      <scroll-view class="container--scroll-view" @scrolltolower="onScrollToLower" scroll-y="true" @scroll="onScrollEvent" :style="'height: ' + scrollHeight + 'px;'">

        <!-- 砍价会场 -->
        <block v-if="currentTab == 0">

          <!-- banner轮播 -->
          <!-- <diy-banner itemStyle="{{ banner.style }}" params="{{ banner.params }}" dataList="{{ banner.data }}"></diy-banner> -->

          <!-- 内容区域 -->
          <view class="bargain-hall">
            <!-- 商品列表 -->
            <view class="main_goods" v-for="(item, index) in activeList.data" :key="index">
				
              <!-- 商品图片 -->
							<picture-group :images="item.wxappgoods.goods.image"></picture-group>
			  
              <view class="main_goods_right">
                <!-- 商品标题 -->
                <view class="main_goods_title_box">
                  <view>
                    <text class="main_goods_title twolist-hidden">{{ item.wxappgoods.goods.goods_name }}</text>
                  </view>
                  <text class="more f-24 col-m" @tap.stop="onTargetActive(item.active_id)">更多<text class="iconfont2 icon-gengduobeifen2 f-24"></text></text>
                </view>
                <!-- 商品信息 -->
                <view class="main_goods_desc">
                  <view class="desc_footer dis-flex flex-y-center">
                    <text class="price_x col-m">¥{{ item.floor_price }}</text>
                    <text class="price_y cl-9">¥{{ item.wxappgoods.goods.goods_sku.goods_price }}</text>
                  </view>
                  <!-- 参与的用户头像 -->
                  <view v-if="item.helps_count > 0" class="peoples dis-flex">
                    <view class="user-list dis-flex">
                      <view v-for="(help, index2) in item.helps" :key="index2" class="user-item-avatar">
                        <image lazy-load :src="help.avatarUrl"></image>
                      </view>
                    </view>
                    <view class="people__text">
                      <text>{{ item.helps_count }}人正在砍价</text>
                    </view>
                  </view>
                  <!-- 规格 -->
                  <view class="sku f-24">
                    <template v-if="item.wxappgoods.goods && item.wxappgoods.goods.goods_multi_spec && item.wxappgoods.goods.goods_multi_spec.spec_attr">
                      <view class="sku_item dis-flex flex-y-center" v-for="(vo, index2) in item.wxappgoods.goods.goods_multi_spec.spec_attr" :key="index2">
                        <text class="sku_title col-9">{{vo.group_name}}</text>
												<view class="onelist-hidden flex-box">
													<text v-for="(vo1, vindx) in vo.spec_items" :key="vindx">
														{{vo1.spec_value}}{{(vo.spec_items.length-1) > vindx ? '/' : ''}}
													</text>
												</view>
                      </view>
                    </template>
                  </view>
                </view>
                <!-- 操作按钮 -->
                <view class="optbox">
                  <!-- <button open-type="contact" type="default-light" class="consultation" sessionFrom="weapp">咨询</button> -->
									<view class="oper-item f-24 col-6" @tap="upload(item.wxappgoods.goods.image)"><text class="iconfont2 icon-download f-30 m-r-10"></text>下载</view>
									<!-- <view class="oper-item f-24 col-6"><text class="iconfont2 icon-synchro f-30"></text>同步</view> -->
                  <button class="settlement" @tap.stop="openDialog(item)">立即参加</button>
                </view>
              </view>
            </view>
            <!-- 无数据提供的页面 -->
						<view class="saler_nodata" v-if="!isLoading && !activeList.data.length">
							<tui-no-data imgUrl="http://pic.kaidanxia.com/2020-06-22/202006221449022b5c05125.png" :imgWidth="264" :imgHeight="264">
								<view class="col-9">亲，暂无砍价活动哦</view>
							</tui-no-data>
						</view>
          </view>
        </block>

        <!-- 我的砍价 -->
        <block v-if="currentTab == 1">
          <!-- 内容区域 -->
          <view class="bargain-hall">
            <!-- 商品列表 -->
            <view class="main_goods" v-for="(item, index) in myList.data" :key="index">
				
              <!-- 商品图片 -->
							<picture-group :images="item.wxappgoods.goods.image"></picture-group>
			  
              <view class="main_goods_right">
                <!-- 商品标题 -->
                <view class="main_goods_title_box">
                  <view>
                    <text class="main_goods_title twolist-hidden">{{ item.wxappgoods.goods.goods_name }}</text>
                  </view>
                  <text class="more f-24 col-m" @tap.stop="onTargetActive(item.active_id)">更多<text class="iconfont2 icon-gengduobeifen2 f-24"></text></text>
                </view>
                <!-- 商品信息 -->
                <view class="main_goods_desc">
                  <view class="desc_footer dis-flex flex-y-center">
                    <text class="price_x col-m">¥{{ item.floor_price }}</text>
                    <text class="price_y cl-9">¥{{ item.wxappgoods.goods.goods_sku.goods_price }}</text>
                  </view>
                  <!-- 砍价进度 -->
                  <view class="task-rate">
                    <block v-if="item.status">
                      <text>已砍</text>
                      <text class="col-m">{{ item.cut_money }}元，</text>
                      <text></text>
                      <text>只差</text>
                      <text class="col-m">{{ item.surplus_money }}元</text>
                      <text></text>
                    </block>
                    <block v-if="item.is_floor">
                      <text>已砍至最低</text>
                      <text class="col-m">{{ item.floor_price }}元</text>
                      <text></text>
                    </block>
                  </view>
                  <!-- 任务状态 -->
                  <view class="task-status dis-flex flex-y-center">
                    <!-- 倒计时 -->
                    <view v-if="item.status" class="count-down dis-flex flex-y-center">
                      <view class="clock-text">
                        <text class="iconfont2 icon-shijian"></text>
                        <text>剩余</text>
                      </view>
                      <view class="clock">
													<tui-countdown :time="countDownList[index]" color="#333" borderColor="#D0D0D0" :size="22" colonColor="#333" :colonSize="24" :scale="true"></tui-countdown>
                      </view>
                    </view>
                    <view v-if="!item.status" class="task-status__text">
                      <text class="col-m">{{ item.is_buy ? '砍价成功' : '已结束' }}</text>
                    </view>
                  </view>
                  <!-- 规格 -->
                  <view class="sku f-24">
                    <template v-if="item.wxappgoods.goods && item.wxappgoods.goods.goods_multi_spec && item.wxappgoods.goods.goods_multi_spec.spec_attr">
                      <view class="sku_item dis-flex flex-y-center" v-for="(vo, index2) in item.wxappgoods.goods.goods_multi_spec.spec_attr" :key="index2">
                        <text class="sku_title col-9">{{vo.group_name}}</text>
												<view class="onelist-hidden flex-box">
													<text v-for="(vo1, vindx) in vo.spec_items" :key="vindx">
														{{vo1.spec_value}}{{(vo.spec_items.length-1) > vindx ? '/' : ''}}
													</text>
												</view>
                      </view>
                    </template>
                  </view>
                </view>
                <!-- 操作按钮 -->
                <view class="optbox">
                  <!-- <button open-type="contact" type="default-light" class="consultation" sessionFrom="weapp">咨询</button> -->
									<view class="oper-item f-24 col-6" @tap="upload(item.wxappgoods.goods.image)"><text class="iconfont2 icon-download f-30 m-r-10"></text>下载</view>
									<!-- <view class="oper-item f-24 col-6"><text class="iconfont2 icon-synchro f-30"></text>同步</view> -->
                  <button class="settlement" v-if="item.status" @tap="onTargetTask" :data-id="item.task_id">继续砍价</button>
                  <button disabled class="settlement" v-else>已结束</button>
                </view>
              </view>
            </view>
            <view v-if="noMore" class="no-more f-28">亲, 没有更多了</view>
            <!-- 无数据提供的页面 -->
						<view class="saler_nodata" v-if="!isLoading && !myList.data.length">
							<tui-no-data imgUrl="http://pic.kaidanxia.com/2020-06-22/202006221449022b5c05125.png" :imgWidth="264" :imgHeight="264">
								<view class="col-9">亲，暂未参与砍价活动哦</view>
							</tui-no-data>
						</view>
          </view>
        </block>
      </scroll-view>

      <!-- 底部选项卡 -->
			<view class="footer">
				<view class="footer-fixed dis-flex">
				  <!-- 砍价会场 -->
				  <view :class="'tabbar-item flex-box ' + ( currentTab == 0 ? 'item__active' : '' )">
				    <form @submit="onToggleTab" data-index="0" report-submit="true">
				      <button formType="submit" class="btn-normal">
				        <view class="tabbar-item-content dis-flex flex-x-center flex-y-center">
				          <view class="tabbar-item-icon">
				            <text class="iconfont2 icon-kanjiashu"></text>
				          </view>
				          <view class="tabbar-item-name">
				            <text>砍价会场</text>
				          </view>
				        </view>
				      </button>
				    </form>
				  </view>
				  <!-- 分割线 -->
				  <view class="tabbar-item__divider">
				    <view class="divider-line"></view>
				  </view>
				  <!-- 我的砍价 -->
				  <view :class="'tabbar-item flex-box ' + ( currentTab == 1 ? 'item__active' : '' )">
				    <form @submit="onToggleTab" data-index="1" report-submit="true">
				      <button formType="submit" class="btn-normal">
				        <view class="tabbar-item-content dis-flex flex-x-center flex-y-center">
				          <view class="tabbar-item-icon">
				            <text class="iconfont2 icon-gerenzhongxin"></text>
				          </view>
				          <view class="tabbar-item-name">
				            <text>我的砍价</text>
				          </view>
				        </view>
				      </button>
				    </form>
				  </view>
				</view>
			</view>
			<!-- 确认购买弹窗 -->
			<proSpecs ref="proSpecs"></proSpecs>
			<download-file @comfirmStatus="comfirmStatusS" ref="download"></download-file>
  </view>
</template>

<script>
import pictureGroup from '@/components/goods/picture-group/index';
const App = getApp().globalData; // 工具类
// 工具类
import util from "@/utils/util"; // 倒计时插件
// 倒计时插件
import CountDown from "@/utils/countdown"; // 记录规格的数组
// 记录规格的数组
let goodsSpecArr = [];
// import diyBanner from "@/components/diy/banner/banner";
import downloadFile from '@/components/download-file';
import proSpecs from '../proSpecs/pro-specs';

export default {
  components: {
    // diyBanner,
		pictureGroup,
		downloadFile,
		proSpecs
  },
  data() {
    return {
      title: '砍价专区',
      //标题
      controls: false,
      // 当前tab索引
      currentTab: 0,
      // 列表容器高度
      scrollHeight: null,
      // 列表容器滚动的位置
      scrollTop: 0,
      noMore: false,
      // 没有更多数据
      isLoading: true,
      // 是否正在加载中
      page: 1,
      // 当前页码
      // 时间记录
      countDownList: [],
      // 砍价会场商品列表
      activeList: [],
      // 我的砍价列表
      myList: [],
      // 砍价弹窗
      goods: {},
      // 商品详情信息
      active_id: '',
      goods_price: 0,
      // 商品价格
      line_price: 0,
      // 划线价格
      stock_num: 0,
      // 库存数量
      goods_num: 1,
      // 商品数量
      goods_sku_id: 0,
      // 规格id
      cart_total_num: 0,
      // 购物车商品总数量
      goodsMultiSpec: {}, // 多规格信息
      floor_price: "",
      // showBottomPopup: false,
			// listNumShow: true,
      sharing_price: "",
      skuCoverImage: "",
    };
  },

  props: {},

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 设置scroll-view高
    this.$nextTick(() => {
      this.setListHeightFun();
    })
    // 设置当前tab索引
    this.setCurrentTabFun(options);
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    let _this = this;

    if (_this.scrollTop == 0) {
      // 获取列表数据
      _this.getListFun();
    }
  },

  methods: {

    /**
    * 用户点击右上角分享
    */
    onShareAppMessage() {
      let _this = this; 
			// 构建页面参数
      let params = getApp().globalData.getShareUrlParams();
      return {
        title: '砍价专区',
        path: `/pages/bargain/index/index?${params}`
      };
    },
		//立即参加
		openDialog(item) {//console.log(item)
			let goods = item.wxappgoods;
			goods.active_id = item.active_id;
			goods.floor_price = item.floor_price;
			this.$refs.proSpecs._open(goods,'buyNow')
		},
    /**
     * 初始化商品多规格
     */
    initManySpecData(data) {
      goodsSpecArr = [];

      for (let i in data.spec_attr) {
        for (let j in data.spec_attr[i].spec_items) {
          if (j < 1) {
            data.spec_attr[i].spec_items[0].checked = true;
            goodsSpecArr[i] = data.spec_attr[i].spec_items[0].item_id;
          }
        }
      }
      return data;
    },

    /**
     * 设置当前tab索引
     */
    setCurrentTabFun(options) {
      let _this = this;

      if (options.hasOwnProperty('tab')) {
        let title = options.tab == 0 ? '砍价专区' : '我的砍价';

        _this.setData({
          currentTab: options.tab,
          title: title
        });
      }
    },

    /**
     * 设置商品列表高度
     */
    setListHeightFun() {
      let _this = this;
      // console.log(_this.$refs.navigationBar)
      const query = uni.createSelectorQuery();
      query.select('#top').boundingClientRect();
      query.selectViewport().scrollOffset();
      query.exec(function (res) {
        let systemInfo = wx.getSystemInfoSync(),
            rpx = systemInfo.windowWidth / 750,
            // 计算rpx
        tapHeight = Math.floor(rpx * (100 + 20)),
            // tap高度
        scrollHeight = systemInfo.windowHeight - tapHeight - res[0].height; // swiper高度

        _this.setData({
          scrollHeight
        });
      });
    },

    /**
     * 获取砍价活动列表
     */
    getActiveList(isPage) {
      let _this = this;

      getApp().globalData._get('index.php', {
        s: '/xapi/bargain.active/lists',
        page: _this.page || 1
      }, result => {
        let resList = result.data.activeList,
            dataList = _this.activeList;

        if (isPage == true) {
          _this.setData({
            'activeList.data': dataList.data.concat(resList.data),
            isLoading: false
          });
        } else {
          _this.setData({
            activeList: resList,
            isLoading: false
          });
        }
      });
    },

    /**
     * 获取我的砍价列表
     */
    getMyList(isPage) {
      let _this = this;

      getApp().globalData._get('bargain.task/lists', {
        page: _this.page || 1
      }, result => {
        let resList = result.data.myList,
            dataList = _this.myList;

        if (isPage == true) {
          _this.setData({
            'myList.data': dataList.data.concat(resList.data),
            isLoading: false
          });
        } else {
          _this.setData({
            myList: resList,
            isLoading: false
          });
        } // 初始化倒计时组件


        _this.initCountDownDataFun(result.data);
      });
    },

    /**
     * 初始化倒计时组件
     */
    initCountDownDataFun(data) {
      let _this = this; // 记录活动到期时间

			//console.log(_this.countDownList)
      let countDownList = _this.countDownList;
			data.myList.data.forEach(item => {
				
				let now_time = Math.round(new Date() / 1000);
				let end_time = Math.round(new Date(item.end_time.replace(/\-/g, '/')).getTime()/1000);
				if(now_time < end_time){
					let time = end_time - now_time;
					
					if (_this.countDownList.length > 0) {
						_this.countDownList.push(time)
					} else {
						_this.countDownList[0] = time;
					}
				}
				
			});

      _this.countDownList = countDownList;
    },

    /**
     * 记录滚动的位置
     */
    onScrollEvent(e) {
      let _this = this;

      _this.setData({
        scrollTop: e.detail.scrollTop
      });
    },

    /**
     * 切换tabbar
     */
    onToggleTab(e) {
      let _this = this; // 保存formid

      _this.setData({
        currentTab: e.currentTarget.dataset.index,
        title: e.currentTarget.dataset.index == 0 ? '砍价专区' : '我的砍价',
        activeList: [],
        myList: [],
        page: 1,
        isLoading: true,
        noMore: false
      }); // 获取列表数据


      _this.getListFun();
    },

    // 参加砍价
    // onTargetGoods(e) {
    //   console.log(e.currentTarget.dataset.id);
    //   uni.navigateTo({
    //     url: `../goods/index?active_id=${e.currentTarget.dataset.id}`
    //   });
    // },

    /**
     * 跳转到砍价商品详情
     */
    onTargetActive(id) {
      // 保存formid
      uni.navigateTo({
        url: `../goods/index?active_id=${id}`
      });
    },

    /**
     * 跳转到砍价任务详情
     */
    onTargetTask(e) {
      // 保存formid
      getApp().globalData.saveFormId(e.detail.formId);
      uni.navigateTo({
        url: `../task/index?task_id=${e.currentTarget.dataset.id}`
      });
    },

    /**
     * 下拉到底部加载下一页
     */
    onScrollToLower() {
      let _this = this,
          listData = _this.currentTab == 0 ? _this.activeList : _this.myList; // 已经是最后一页


      if (_this.page >= listData.last_page) {
        _this.setData({
          noMore: true
        });

        return false;
      } // 加载下一页列表


      _this.setData({
        page: ++_this.page
      });

      _this.getListFun(true);
    },

    /**
     * 获取列表数据
     */
    getListFun(isPage) {
      let _this = this;

      _this.currentTab == 0 ? _this.getActiveList(isPage) : _this.getMyList(isPage);
    },
		// 点击下载
		upload(files){
			const that = this;
			let uploads = [];
			files.forEach(item => {
				uploads.push(item.file_path)
			});
			if(uploads!=''){
				uni.showModal({
					title: '友情提示',
					content: '是否下载该商品的图片/视频？',
					confirmColor: '#E82E2E',
					confirmText: '是',
					cancelText: '否',
					success: (res) => {
						if(res.confirm){
							that.$refs.download._downloadFileS(uploads);
						}
					}
				});
			}else{
				that.$api.msg('该商品暂无可下载的图片/视频');
			}
		},
		comfirmStatusS (promise) {
			promise.then((res) => {
				uni.hideLoading();
				uni.hideToast();
				this.$api.msg(res?"保存成功~":'取消保存')
			})
		},
  }
};
</script>
<style lang="scss" scoped>
	@import "./index.scss";
	/deep/ .tui-countdown-item{
		border-color: transparent !important;
		box-shadow:0 0 2rpx 0 #D0D0D0;
	}
</style>